from django.contrib.auth import logout
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from rest_framework import permissions, status
from rest_framework.authentication import SessionAuthentication, BasicAuthentication
from rest_framework.permissions import IsAuthenticated
from rest_framework.views import APIView
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
from rest_framework_simplejwt.views import TokenObtainPairView

from utils.config import CacheKeys
from utils.others import user_create_email_html, get_ver_code
from wangshihe import settings
from .models import EmailSender, EmailRecipient
from .serializers import MyTokenObtainPairSerializer, EmailSenderSerializer, UserDefaultSerializer
from utils.network import Result, CustomGenericViewSet, EmailUtil
from django.core.cache import cache


def get_email_create(to) -> (EmailSender, int):
    redis_key = CacheKeys.CREATE_USER + to
    code = get_ver_code(redis_key)
    email_sender = EmailSender(**{
        'from_email': settings.EMAIL_HOST_USER,
        'title': '注册万事和大数据',
        'message': '以下是注册万事和大数据的验证码...',
        'content': user_create_email_html(code),
    })
    email_sender.save()
    email_recipient = EmailRecipient(name=to, from_email=email_sender)
    email_recipient.save()
    return email_sender, code


class UserViews(CustomGenericViewSet):

    def create(self, request):
        """注册账号"""
        data = request.data
        email = data['email']
        sms = data['sms']
        redis_key = CacheKeys.CREATE_USER + email
        if sms is None and not cache.has_key():
            email_sender, code = get_email_create(email)
            if isinstance(email_sender, EmailSender):
                serializer = EmailSenderSerializer(EmailSender.objects.get(id=email_sender.id))
                email_data = serializer.data
                EmailUtil.send_sms(email_data)
                return Result.success(data=email_data)
            else:
                raise email_sender
        elif sms is None:
            return Result.error(code=status.HTTP_400_BAD_REQUEST, message='请先填写验证码')
        elif sms != cache.get(redis_key):
            return Result.error(code=status.HTTP_400_BAD_REQUEST, message='验证码错误')
        else:
            data.setdefault('username', email)
            data.pop('sms')
            user_new = User.objects.create_user(**data)
            serializer = UserDefaultSerializer(user_new)
            return Result.success(data=serializer.data)


class LogoutView(APIView):
    """当前登录的用户信息"""
    authentication_classes = [JSONWebTokenAuthentication, SessionAuthentication, BasicAuthentication]
    permission_classes = [IsAuthenticated]

    def post(self, request):
        logout(request)
        return Result.success(message='登出成功')


class MyInfoView(APIView):
    """当前登录的用户信息"""
    authentication_classes = [JSONWebTokenAuthentication, SessionAuthentication, BasicAuthentication]
    permission_classes = [IsAuthenticated]

    def post(self, request):
        serializer = UserDefaultSerializer(request.user)
        return Result.success(data=serializer.data)


class MyTokenObtainPairView(TokenObtainPairView):
    serializer_class = MyTokenObtainPairSerializer
